using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Web;
using System.Web.Caching;
using log4net;

namespace Ray.Web.HttpModules
{
    /// <summary>
    /// http://www.aspnetresources.com/blog/fighting_view_state_spam.aspx
    /// Copyright (c) 2004-2006, Milan Negovan 
    /// http://www.AspNetResources.com
    /// All rights reserved.
    ///
    /// Redistribution and use in source and binary forms, with or without 
    /// modification, are permitted provided that the following conditions 
    /// are met:
    ///
    ///    * Redistributions of source code must retain the above copyright 
    ///      notice, this list of conditions and the following disclaimer.
    ///      
    ///    * Redistributions in binary form must reproduce the above copyright 
    ///      notice, this list of conditions and the following disclaimer in 
    ///      the documentation and/or other materials provided with the 
    ///      distribution.
    ///      
    ///    * The name of the author may not be used to endorse or promote products
    ///      derived from this software without specific prior written permission.
    ///
    /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
    /// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 
    /// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
    /// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
    /// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
    /// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
    /// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
    /// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
    /// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
    /// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
    /// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    /// 
    /// 2007-09-23 Joe Audette added logging with log4net
    /// 2007-09-24 Joe Audette changed so that banned ips are stored in the db
    /// instead of text file
    /// </summary>
    public class BannedIPBlockingHttpModule : IHttpModule
    {
        private static readonly ILog log
            = LogManager.GetLogger(typeof(BannedIPBlockingHttpModule));


        public void Init(HttpApplication application)
        {
            application.Error += new EventHandler(this.Error);
            application.BeginRequest += new EventHandler(BeginRequest);
            application.EndRequest += new EventHandler(this.EndRequest);
        }

        
        private void BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = ((HttpApplication)sender);
            HttpContext context = app.Context;
            string ip = context.Request.UserHostAddress;

            if (!IsBanned(ip)) return;

            AbortRequestFromBannedIp(context);
        }

       
        private void Error(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;


            /* There are numerous ways to screw up view state, but it should always be Base64-encoded. 
               Spammers try to plug emails into view state in plain text, and we can look for '@' since
               it's not allowed in Base64. It's a smoke test, but it should serve its purpose well.
               
               We'll try to extract view state from the Form collection and see what we're dealing with.
               The exception we receive here is too generic to tell.
            */
            string viewState = context.Request.Form["__VIEWSTATE"];

            if (viewState == null || viewState.Length == 0)
                return;
            // this is ony detecting if @ is present
            // this doesn't catch all manipulation
            // just some common manipulation where apprently
            // email spam is posted in viewstate
            if (HttpUtility.HtmlDecode(viewState).IndexOf('@') == -1)
                return;

            app.Context.Server.ClearError();

            /* Blacklist these sons of bitches */
            AddIpToBanList(context);
            AbortRequestFromBannedIp(context);
        }

        
        private void EndRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;
            HttpResponse response = context.Response;


            if (!context.Items.Contains("BanCurrentRequest"))
                return;

            response.ClearContent();
            response.SuppressContent = true;
            response.StatusCode = 403;
            response.StatusDescription = "Access denied: your IP has been banned. Don't push your luck spamming me.";
        }

        
        private void AddIpToBanList(HttpContext context)
        {
            //string ip = context.Request.UserHostAddress;

            //if (IsBanned(ip)) return; //already banned

            //BannedIPAddress ipToBan = new BannedIPAddress();
            //ipToBan.BannedIP = ip;
            //ipToBan.BannedUTC = DateTime.UtcNow;
            //ipToBan.BannedReason = "detected viewstate manipulation";
            //ipToBan.Save();

            //String pathToCacheDependencyFile
            //        = HttpContext.Current.Server.MapPath(
            //    "~/Data/bannedipcachedependency.config");
            //CacheHelper.TouchCacheFile(pathToCacheDependencyFile);

            //log.Info("BannedIPBlockingHttpModule banned ip address " + ip);
        }

        
        private static void AbortRequestFromBannedIp(HttpContext context)
        {
            context.Items["BanCurrentRequest"] = true;
            context.ApplicationInstance.CompleteRequest();
            log.Info("BannedIPBlockingHttpModule blocked request from banned ip address " + context.Request.UserHostAddress);
        }

        private bool IsBanned(string ip)
        {
            //List<String> bannedIPs = CacheHelper.GetBannedIPList();
            //if(bannedIPs.Contains(ip))return true;
            return false;

        }

        
        public void Dispose() { }
    }
}